﻿/* 
 *  <copyright file="CGuid.cs" company="Wesley Jowitt">
 *  
 *  SobrietyEngine: Copyright (c) 2011 Wesley Jowitt
 *  
 *  This software is distributed under a software license.
 *   * As of the creation time of this file, the license in use is the Microsoft Permissive License (Ms-PL) 
 *    * The license can be viewed at:
 *     * License.Txt in the root folder of this project
 *      * http://sobrietyengine.codeplex.com/license
 *       * http://www.microsoft.com/opensource/licenses.mspx
 *       
 *  </copyright>
 *   */

using System;
using System.Collections.Generic;
using SobrietyEngine.Common;
using SobrietyEngine.Logging;


namespace SobrietyEngine.Assets.Textures
{
    class AnimationSetReader
    {
        
        public static AnimationData Load(String data)
        {           
            //runs through the UDMF formated text and loads all items
            StringData sd = StringData.ReadData(ref data);
            
            //lets iterate through each item in the stringdata we just loaded form the UDMF file
            AnimationData ad = new AnimationData();

            ad.AnimationSetName = sd.Data["name"];

            foreach (StringData sdat in sd.SubTokens)
            {
                if (sdat.Token == "animation")
                {
                    List<FrameData> fd = new List<FrameData>();
                    String name = sdat.Data["name"];
                    float time = float.Parse(sdat.Data["time"]);
                    string textureName = sdat.Data["textureName"];
                    
                    //if there is a # sign, we load the textures in number order.
                    //this needs improvement, badly. this was hardcoded to match output
                    //generated by some program used by our artist during a hack session 
                    //quite a while ago. 
                    if (textureName.Contains("#"))
                    {
                        int numFrames = Int16.Parse(textureName.Split('#')[1]);
                        String texName = textureName.Split('#')[0];
                        String leadingZeros = "00";
                        for (int frame = 0; frame < numFrames; frame++)
                        {
                            fd.Add(new FrameData(texName + leadingZeros + frame, time));
                            if (frame == 9)
                                leadingZeros = "0";
                        }
                    }

                    ad.Animations.Add(name, fd);
                }
                else
                {
                    Logging.Logger.Error("AnimationSetReader:: unrecognized token " + sdat.Token);
                }
            }

            return ad;
        }

    }
}
